package com.app.service.impl.article;

import com.app.domain.po.article.ArticleCountPo;
import com.app.domain.vo.article.ArticleCountVo;
import com.app.domain.vo.article.ArticleVo;
import com.app.framework.utils.CollectionUtils;
import com.app.mapper.article.ArticleCountMapper;
import com.app.service.article.ArticleCountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文章计数器方法方法实现
 */
@Service
public class ArticleCountServiceImpl extends ServiceImpl<ArticleCountMapper, ArticleCountPo> implements ArticleCountService {

    /**
     * 批量查询文章计数器
     *
     * @param articleIds 文章ID集合
     */
    @Override
    public List<ArticleCountVo> batchSelectArticleCounts(List<Long> articleIds) {
        return baseMapper.batchSelectArticleCounts(articleIds);
    }

    /**
     * 查询文章计数器
     *
     * @param articleId 文章ID
     */
    @Override
    public ArticleCountVo selectArticleCounts(Long articleId) {
        return baseMapper.selectArticleCounts(articleId);
    }

    /**
     * 更新文章点赞数量
     *
     * @param articleId 文章ID
     */
    @Override
    public void updateArticleLikes(Long articleId) {
        baseMapper.updateArticleLikes(articleId);
    }

    /**
     * 更新文章访问数量
     *
     * @param articleId 文章ID
     */
    @Override
    public void updateArticleLooks(Long articleId) {
        baseMapper.updateArticleLooks(articleId);
    }

    /**
     * 更新文章评论数量
     *
     * @param articleId 文章ID
     * @param count     评论数量
     */
    @Override
    public void updateArticleComments(Long articleId, Integer count) {
        baseMapper.updateArticleComments(articleId, count);
    }

    /**
     * 批量写入文章计数器
     *
     * @param articleVos 文章Vos
     */
    public void batchSetArticleCounts(List<ArticleVo> articleVos) {
        if (CollectionUtils.isEmpty(articleVos)) {
            return;
        }
        List<Long> articleIds = new ArrayList<>();
        for (ArticleVo articleVo : articleVos) {
            articleIds.add(articleVo.getId());
        }
        if (!articleIds.isEmpty()) {
            List<ArticleCountVo> articleCountVos = baseMapper.batchSelectArticleCounts(articleIds);
            Map<Long, ArticleCountVo> articleCountVoMap = new HashMap<>();
            for (ArticleCountVo articleCountVo : articleCountVos) {
                articleCountVoMap.put(articleCountVo.getArticleId(), articleCountVo);
            }
            for (ArticleVo articleVo : articleVos) {
                ArticleCountVo articleCountVo = articleCountVoMap.get(articleVo.getId());
                if (articleCountVo != null) {
                    articleVo.setArticleCount(articleCountVo);
                }
            }
        }
    }

}